var chart;//图表
var refresh;//刷新数据
var deviceId = $('#deviceId').val();//要显示的设备ID号
var deviceTime = $('#deviceDate').val();//要显示信息的日期
var dataLength;//获取到的日期数据量
var dom = document.getElementById('chart-view');
var flag = false;//判断是不是当日数据，如果是，则一秒刷新一次，否则只加载一次，不再刷新
var nowDate;

$(document).ready(function () {
    nowDate = getNowDate();
    //图表初始化
    selectDevice();
    if (dataLength == 0) {
        $("#no_chart_data").css("display", "block");
    } else {
        $("#no_chart_data").css("display", "none");
        chart = echarts.init(dom);
        loadingTips();
        doChart();
    }

    //每隔1秒刷新一次图表
    if ($.trim(nowDate)== $.trim(deviceTime)){
        refresh = setInterval(doChart, 1000);
    }
});

//鼠标移入图表界面，停止刷新数据
$("#chart-view").on('mouseover', function () {
    clearInterval(refresh);
});
//鼠标移出图表界面，刷新数据
$("#chart-view").on('mouseout', function () {
    if (dataLength != 0) {
        if ($.trim(nowDate)== $.trim(deviceTime)){//请求监控数据的日期不是当天日期，停止刷新
            refresh = setInterval(doChart, 1000);
        }
    }
});

//显示所有设备
function selectDevice() {
    $.ajax({
        method: "POST",
        async: false,
        url: "getDevice.do",
        success: function (data) {
            var deviceData = JSON.parse(data);
            var str = null;
            for (var index in deviceData) {
                str += "<option value=" + deviceData[index].gd_dev_id + ">" + deviceData[index].gd_dev_name + "</option>";
                $("#deviceId").html(str);
            }
        }
    });
    $("#deviceId").get(0).selectedIndex = 0;
    deviceId = $("#deviceId").val();
    selectTime();
}

//显示设备数据所有的日期
function selectTime() {
    dataLength = 0;//json数据长度
    $.ajax({
        method: "POST",
        async: false,
        url: "getDeviceDate.do",
        data: {"gd_dev_id": deviceId},
        success: function (data) {
            var deviceData = JSON.parse(data);
            for (var index in deviceData) {
                dataLength++;
            }
            var str = null;
            for (var index in deviceData) {
                str += "<option value=" + deviceData[index] + ">" + deviceData[index] + "</option>";
                $("#deviceDate").html(str);
            }
            $("#deviceDate").get(0).selectedIndex = 0;
            deviceTime = $("#deviceDate").val();
        },
        error: function () {
            dataLength = 0;
        }
    });
}

//改变设备
function changDevice() {
    deviceId = $('#deviceId').val();
    $("#deviceDate").html("<option value='暂无数据'>暂无数据</option>");
    deviceTime = "暂无数据";
    selectTime();
    changTime();

}

//改变时间
function changTime() {
    deviceTime = $('#deviceDate').val();
    if (dataLength == 0){
        $("#no_chart_data").css("display", "block");
        $("#chart-view").removeAttr("_echarts_instance_").empty();
        chart.dispose();
    }else{
        if ($.trim(nowDate)== $.trim(deviceTime)){//请求监控数据的日期不是当天日期，停止刷新
            refresh = setInterval(doChart, 1000);
        }
        loadingTips();
        doChart();
    }
}

function loadingTips() {
    chart.showLoading({
        text: "正在加载图表数据...",
        x: "center",
        y: "center",
        textStyle: {
            color: "red",
            fontSize: 20
        },
        effect: "spin"
    });
}

//获取信息并绘制图表
function doChart() {
    if (dataLength == 0) {
        $("#no_chart_data").css("display", "block");
        $("#chart-view").removeAttr("_echarts_instance_").empty();
        chart.dispose();
    } else {
        $("#no_chart_data").css("display", "none");
        chart = echarts.init(dom);
        $.ajax({
            method: "POST",
            url: "showDeviceData.do",
            data: {"gd_dev_id": deviceId, "date": deviceTime},
            success: function (data) {
                chart.hideLoading();
                chartConf(data);
            }
        });
    }
}


//图表配置
function chartConf(data) {
    var deviceData = JSON.parse(data);
    //配置图表属性项
    //X轴的值
    var xData = deviceData.map((item, index) => {
        var date = new Date(item.gd_dev_time);
        return date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    });
    //数据区域显示起始值
    var startDate = new Date(deviceData[Object.keys(deviceData).length - 14].gd_dev_time);
    var start = startDate.getHours() + ":" + startDate.getMinutes() + ":" + startDate.getSeconds();

    //各气体含量的值
    var yData_O2 = deviceData.map((item, index) => {
        return item.gd_dev_O2;
    });
    var yData_H2S = deviceData.map((item, index) => {
        return item.gd_dev_H2S;
    });
    var yData_CH4 = deviceData.map((item, index) => {
        return item.gd_dev_CH4;
    });
    var yData_TEMP = deviceData.map((item, index) => {
        return item.gd_dev_TEMP;
    });
    var yData_Rh = deviceData.map((item, index) => {
        return item.gd_dev_Rh;
    });


    //有数据时的图表配置项
    var option = {//有数据时的图表配置项
        title: {
            text: '数据监控',
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            right: '35%',
            pageTextStyle: {
                fontSize: 15
            },
            data: [
                {
                    name: '氧气含量'
                },
                {
                    name: 'H2S含量'
                },
                {
                    name: 'CH4含量'
                },
                {
                    name: '温度值'
                },
                {
                    name: '湿度值'
                }]
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xData
        },
        yAxis: {
            type: 'value'
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        dataZoom:
            [{startValue: start},
                {type: 'inside'}
            ],
        series: [
            {
                name: '氧气含量',
                type: 'line',
                smooth: true,
                data: yData_O2,
                itemStyle: {
                    color: '#1093ff'
                },
            },
            {
                name: 'H2S含量',
                type: 'line',
                smooth: true,
                data: yData_H2S,
                itemStyle: {
                    color: '#feff14'
                }
            },
            {
                name: 'CH4含量',
                type: 'line',
                smooth: true,
                data: yData_CH4,
                itemStyle: {
                    color: 'black'
                }
            },
            {
                name: '温度值',
                type: 'line',
                smooth: true,
                data: yData_TEMP,
                itemStyle: {
                    color: '#ff19a3'
                }
            },
            {
                name: '湿度值',
                type: 'line',
                smooth: true,
                data: yData_Rh,
                itemStyle: {
                    color: '#8bff0a'
                }
            }
        ]
    };
    chart.setOption(option, true);
    //获取最新的数据值
    var gd_dev_O2_data = deviceData[Object.keys(deviceData).length - 1].gd_dev_O2;
    var gd_dev_H2S_data = deviceData[Object.keys(deviceData).length - 1].gd_dev_H2S;
    var gd_dev_CH4_data = deviceData[Object.keys(deviceData).length - 1].gd_dev_CH4;
    if ($.trim(nowDate) == $.trim(deviceTime)) {
        warning(gd_dev_O2_data, gd_dev_H2S_data, gd_dev_CH4_data);
    }
}


// 获取当前日期时间
function getNowDate() {
    var date = new Date();
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() + ' ';
    return Y + M + D;
}

//气体含量超标提醒
function warning(gd_dev_O2_data,gd_dev_H2S_data,gd_dev_CH4_data) {
    if (parseFloat(gd_dev_O2_data)>=23 ||parseFloat(gd_dev_H2S_data)>=10||parseFloat(gd_dev_CH4_data)>=100 ){
        var email = $("#user_email").val();
        $.ajax({
            method: "POST",
            url: "sendEmail.do",
            data: {"gd_dev_O2_data": gd_dev_O2_data, "gd_dev_H2S_data": gd_dev_H2S_data,"gd_dev_CH4_data":gd_dev_CH4_data,"email":email},
        });
    }

    if (parseFloat(gd_dev_O2_data)>=23){
        alert("氧气含量超标，请注意！！！");
    }
    if (parseFloat(gd_dev_H2S_data)>=10){
        alert("硫化氢含量超标，请注意！！！");
    }
    if (parseFloat(gd_dev_CH4_data)>=100){
        alert("甲烷含量超标，请注意！！！");
    }
}
